package com.xdw.vuebackdemo.interceptor;

import com.xdw.vuebackdemo.base.common.ApiCodeConstant;
import com.xdw.vuebackdemo.base.common.MyException;
import com.xdw.vuebackdemo.permission.RequiredPermission;
import com.xdw.vuebackdemo.service.PermissionService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
 * @author xiadewang
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {
    private static Logger log = LoggerFactory.getLogger(PermissionInterceptor.class);
    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从上一个登录验证拦截器中获取userid
        log.info("mmm="+request.getAttribute("userId"));
        long userId = Long.parseLong(String.valueOf(request.getAttribute("userId")));
        // 验证权限
        if (this.hasPermission(handler,userId)) {
            log.info("hasPermission");
            request.setAttribute("userId",userId);
            return true;
        }
        log.info("No Permission");
        //  null == request.getHeader("x-requested-with") TODO 暂时用这个来判断是否为ajax请求
        // 如果没有权限 则抛403异常 springboot会处理，跳转到 /error/403 页面
//        response.sendError(HttpStatus.FORBIDDEN.value(), "无权限");
        throw new MyException(ApiCodeConstant.RESULT_PERMISSION_EXCEPTION,"无权限");
//        return false;
    }

    /**
     * 是否有权限
     *
     * @param handler
     * @return
     */
    private boolean hasPermission(Object handler,long userId) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            RequiredPermission requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
            // 如果方法上的注解为空 则获取类的注解
            if (requiredPermission == null) {
                requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
            }
            // 如果标记了注解，则判断权限
            if (requiredPermission != null && StringUtils.isNotBlank(requiredPermission.value())) {
                // redis或数据库 中获取该用户的权限信息 并判断是否有权限,优先从redis获取
                List<String> permissionNameList = permissionService.getPermissionNameListByUserId(userId);
                if (CollectionUtils.isEmpty(permissionNameList) ){
                    return false;
                }
                return permissionNameList.contains(requiredPermission.value());
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // TODO
    }
}
